/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package com.zhifei.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 日期处理
 *
 * @author Mark sunlightcs@gmail.com
 */
public class DateUtil extends org.apache.commons.lang3.time.DateUtils {
    /**
     * 时间格式(yyyy-MM-dd)
     */
    public final static String DATE_PATTERN = "yyyy-MM-dd";
    /**
     * 时间格式(yyyy-MM-dd HH:mm:ss)
     */
    public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_FORMAT_DATEYEAR = "yyyy"; // 年
    public static final String DATE_FORMAT_DATEMONTN = "yyyy-MM"; // 年-月
    public static final String DATE_FORMAT_DATEDAY = "yyyy-MM-dd"; // 年-月-日
    public static final String DATE_FORMAT_DATESHORTDAY = "yyyyMMdd"; // 年月日
    public static final String DATE_FORMAT_TIME = "HH:mm:ss"; // 时:分:秒
    public static final String DATE_FORMAT_DATETIME = "yyyy-MM-dd HH:mm:ss"; // 年-月-日 时:分:秒
    public static final String DATE_FORMAT_DATETIMEMS = "yyyyMMddHHmmss"; // 年月日时分秒

    public static  String DATE_FORMAT_DATETIME_ISO = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; // 年-月-日 时:分:秒
    public static  SimpleDateFormat sdfDateTime_ISO = new SimpleDateFormat(DATE_FORMAT_DATETIME_ISO);

    public static final SimpleDateFormat sdfDateYear = new SimpleDateFormat(DATE_FORMAT_DATEYEAR);
    public static final SimpleDateFormat sdfDateMonth = new SimpleDateFormat(DATE_FORMAT_DATEMONTN);
    public static final SimpleDateFormat sdfDateDay = new SimpleDateFormat(DATE_FORMAT_DATEDAY);
    public static final SimpleDateFormat sdfDateShortDay = new SimpleDateFormat(DATE_FORMAT_DATESHORTDAY);
    public static final SimpleDateFormat sdfTime = new SimpleDateFormat(DATE_FORMAT_TIME);
    public static final SimpleDateFormat sdfDateTime = new SimpleDateFormat(DATE_FORMAT_DATETIME);
    public static final SimpleDateFormat sdfDateTimeMS = new SimpleDateFormat(DATE_FORMAT_DATETIMEMS);

    /**
     * 日期格式化 日期格式为：yyyy-MM-dd
     *
     * @param date 日期
     * @return 返回yyyy-MM-dd格式日期
     */
    public static String format(Date date) {
        return format(date, DATE_PATTERN);
    }

    /**
     * 日期格式化 日期格式为：yyyy-MM-dd
     *
     * @param date    日期
     * @param pattern 格式，如：DateUtils.DATE_TIME_PATTERN
     * @return 返回yyyy-MM-dd格式日期
     */
    public static String format(Date date, String pattern) {
        if (date != null) {
            SimpleDateFormat df = new SimpleDateFormat(pattern);
            return df.format(date);
        }
        return null;
    }

    /**
     * 日期解析
     *
     * @param date    日期
     * @param pattern 格式，如：DateUtils.DATE_TIME_PATTERN
     * @return 返回Date
     */
    public static Date parse(String date, String pattern) {
        try {
            return new SimpleDateFormat(pattern).parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 字符串转换成日期
     *
     * @param strDate 日期字符串
     * @param pattern 日期的格式，如：DateUtils.DATE_TIME_PATTERN
     */
    public static Date stringToDate(String strDate, String pattern) {
        if (StringUtils.isBlank(strDate)) {
            return null;
        }

        DateTimeFormatter fmt = DateTimeFormat.forPattern(pattern);
        return fmt.parseLocalDateTime(strDate).toDate();
    }

    /**
     * 根据周数，获取开始日期、结束日期
     *
     * @param week 周期  0本周，-1上周，-2上上周，1下周，2下下周
     * @return 返回date[0]开始日期、date[1]结束日期
     */
    public static Date[] getWeekStartAndEnd(int week) {
        DateTime dateTime = new DateTime();
        LocalDate date = new LocalDate(dateTime.plusWeeks(week));

        date = date.dayOfWeek().withMinimumValue();
        Date beginDate = date.toDate();
        Date endDate = date.plusDays(6).toDate();
        return new Date[]{beginDate, endDate};
    }

    /**
     * 对日期的【秒】进行加/减
     *
     * @param date    日期
     * @param seconds 秒数，负数为减
     * @return 加/减几秒后的日期
     */
    public static Date addDateSeconds(Date date, int seconds) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusSeconds(seconds).toDate();
    }

    /**
     * 对日期的【分钟】进行加/减
     *
     * @param date    日期
     * @param minutes 分钟数，负数为减
     * @return 加/减几分钟后的日期
     */
    public static Date addDateMinutes(Date date, int minutes) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusMinutes(minutes).toDate();
    }

    /**
     * 对日期的【小时】进行加/减
     *
     * @param date  日期
     * @param hours 小时数，负数为减
     * @return 加/减几小时后的日期
     */
    public static Date addDateHours(Date date, int hours) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusHours(hours).toDate();
    }

    /**
     * 对日期的【天】进行加/减
     *
     * @param date 日期
     * @param days 天数，负数为减
     * @return 加/减几天后的日期
     */
    public static Date addDateDays(Date date, int days) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusDays(days).toDate();
    }

    /**
     * 计算day天后的时间
     * @param date
     * @param day
     * @return
     */
    public static Date addDay(Date date, int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, day);
        return calendar.getTime();
    }

    /**
     * 对日期的【周】进行加/减
     *
     * @param date  日期
     * @param weeks 周数，负数为减
     * @return 加/减几周后的日期
     */
    public static Date addDateWeeks(Date date, int weeks) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusWeeks(weeks).toDate();
    }

    /**
     * 对日期的【月】进行加/减
     *
     * @param date   日期
     * @param months 月数，负数为减
     * @return 加/减几月后的日期
     */
    public static Date addDateMonths(Date date, int months) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusMonths(months).toDate();
    }


    /**
     * 对日期的【年】进行加/减
     *
     * @param date  日期
     * @param years 年数，负数为减
     * @return 加/减几年后的日期
     */
    public static Date addDateYears(Date date, int years) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusYears(years).toDate();
    }


    public static Long getNextDayZero() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.add(Calendar.DATE, 1);
        long date = calendar.getTime().getTime();
        return date;
    }

    public synchronized static String getShowDate(Date date, SimpleDateFormat mdsdf) {
        long current = System.currentTimeMillis();
        long ldate = date.getTime();
        long seconds = (current - ldate) / 1000;
        if (seconds >= 0 && seconds <= 60) {
            return "刚刚";
        } else if (seconds / 60 < 60 && seconds / 60 >= 1) {
            return seconds / 60 + "分钟前";
        } else if (seconds / 3600 < 24 && seconds / 3600 >= 1) {
            return seconds / 3600 + "小时前";
        } else if (seconds / (3600 * 24) < 30 && seconds / (3600 * 24) >= 1) {
            return seconds / (3600 * 24) + "天前";
        }
        return mdsdf.format(date);
    }

    public static Date strToDate(String str){
        Date parseDate = null;
        try {
            parseDate = parseDate(str, DATE_FORMAT_DATETIME);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return parseDate;
    }

    /**
     * 字符转换日期
     * @param str
     * @param pattern
     * @return
     */
    public static Date strToDate(String str, String pattern){
        Date parseDate = null;
        try {
            parseDate = parseDate(str, pattern);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return parseDate;
    }

    /**
     * 日期转换字符
     * @param date
     * @return
     */
    public static String dateToStr(Date date){
        return dateToStr(date,DATE_FORMAT_DATETIME);
    }
    /**
     * 日期转换字符
     * @param date
     * @param pattern
     * @return
     */
    public static String dateToStr(Date date, String pattern){
        String dateStr = null;
        if(date == null){
            return dateStr;
        }
        if(DATE_FORMAT_DATEYEAR.equals(pattern)){
            dateStr = sdfDateYear.format(date);
        }else if(DATE_FORMAT_DATEMONTN.equals(pattern)){
            dateStr = sdfDateMonth.format(date);
        }else if(DATE_FORMAT_DATEDAY.equals(pattern)){
            dateStr = sdfDateDay.format(date);
        }else if(DATE_FORMAT_DATESHORTDAY.equals(pattern)){
            dateStr = sdfDateShortDay.format(date);
        }else if(DATE_FORMAT_TIME.equals(pattern)){
            dateStr = sdfTime.format(date);
        }else if(DATE_FORMAT_DATETIME.equals(pattern)){
            dateStr = sdfDateTime.format(date);
        }else if(DATE_FORMAT_DATETIMEMS.equals(pattern)){
            dateStr = sdfDateTimeMS.format(date);
        }else if(DATE_FORMAT_DATETIME_ISO.equals(pattern)){
            dateStr = sdfDateTime_ISO.format(date);
        }else{
            dateStr = "";
        }
        return dateStr;
    }

    /**
     * 字符转日期
     * @param dateStr
     * @return
     */
    public static Date getDateByStr(String dateStr) {
        SimpleDateFormat formatter = null;
        if (dateStr == null) {
            return null;
        } else if (dateStr.length() == 10) {
            formatter = new SimpleDateFormat("yyyy-MM-dd");
        } else if (dateStr.length() == 13) {
            formatter = new SimpleDateFormat("yyyy-MM-dd HH");
        } else if (dateStr.length() == 16) {
            formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        } else if (dateStr.length() == 19) {
            formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        } else if (dateStr.length() > 19) {
            dateStr = dateStr.substring(0, 19);
            formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        } else {
            return null;
        }
        try {
            return formatter.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String formatDateTime(long time) {
        return formatDateTime(time,2);
    }

    public static String formatDateTime(long time, int type) {
        SimpleDateFormat df;
        switch (type) {
            case 0:
                df = new SimpleDateFormat("yyyy-MM-dd");
                break;
            case 1:
                df = new SimpleDateFormat("HH:mm:ss");
                break;
            case 2:
                df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                break;
            case 3:
                df = new SimpleDateFormat("MM-dd");
                break;
            case 4:
                df = new SimpleDateFormat("HH:mm");
                break;
            case 5:
                df = new SimpleDateFormat("MM-dd HH:mm:ss");
                break;
            case 6:
                df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
                break;
            case 7:
                df = new SimpleDateFormat("yyyyMMddHHmmssS");
                break;
            case 8:
                df = new SimpleDateFormat("MMddHHmmss");
                break;
            case 9:
                df = new SimpleDateFormat("yyyyMMdd");
                break;
            case 10:
                df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                break;
            case 11:
                df = new SimpleDateFormat("yyyy,MM,dd,HH:mm");
                break;
            default:
                df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                break;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(time);
        return df.format(cal.getTime());
    }

    /**
     * 获得当前的时间戳
     * @return
     */
    public static Timestamp getCurrentTimeStamp() {
        return new Timestamp(System.currentTimeMillis());
    }

    /**
     * 获得当前日期
     * @return
     */
    public static Date getCurrentDate() {
        return new Date();
    }

    /**
     * 获得当前日期(date)
     * @return
     */
    public static String getCurrentDateStr() {
        return dateToStr(new Date(),DATE_FORMAT_DATEDAY);
    }

    /**
     * 获取当前日期 (datetime)
     * @return
     */
    public static String getCurrentDateTimeStr() {
        return dateToStr(new Date(),DATE_FORMAT_DATETIME);
    }

}
